<?php


namespace app\service;

use app\model\ProductLike;
use app\model\Products;
use app\model\ProductTags;
use app\service\MiniProgramService;

class ProductService
{

    // 产品模型
    protected $productModel;

    public function __construct()
    {
        $this->productModel = new Products();
    }

    // 获取产品详情
    public function getNormalProductDetail($goodsId)
    {
        $product = $this->productModel->where('id', $goodsId)
            ->with(['seller' => function ($query) {
                $query->field('id,store_name,logo,description');
            }, 'brand', 'skus', 'description'])
            ->find();
        if (!$product) {
            throw new \Exception('商品不存在');
        }
        $product = $product->toArray();
        if ($product['approved_status'] != 1) {
            throw new \Exception('商品未审核');
        }
        if ($product['active'] != 1) {
            throw new \Exception('商品已下架');
        }
        if (empty($product['seller'])) {
            $product['shop'] = [
                'id' => 0,
                'store_name' => '平台自营',
                'logo' => '',
                'description' => '专注高品质旅行体验'
            ];
        } else {
            $product['shop'] = $product['seller'];
            unset($product['seller']);
        }
        $product['total_stock']=0;
        // $labelTag = $product['lable_tag'];
        // $product['lable_tag'] = [];
        // if (!empty($labelTag)) {
        //     $tags = ProductTags::where('id', 'in', $labelTag)->field('name')->select()->toArray();
        //     $product['lable_tag'] = array_column($tags, 'name');
        // }
     
        if (!empty($product['skus'])) {
            $skuformat = $this->buildSkuTreeAndList($product['variables'], $product['skus']);
            $product['skuTree'] = $skuformat['skuTree'];
            $product['skuList'] = $skuformat['skuList'];
            foreach ($product['skus'] as $val) {
                $product['total_stock'] += $val['quantity'];
            }
            // $skuTree = [];
            // $skuList = [];

            // foreach ($product['variables'] as $key => $item) {
            //     $children = [];
            //     foreach ($item['values'] as $k => $item2) {
            //         $children[] = [
            //             'id' => ($k + 1),
            //             'name' => $item2['name']['zh_cn'],
            //         ];
            //     }
            //     $skuTree[] = [
            //         'label' => $item['name']['zh_cn'],
            //         'name' => ($item['name']['zh_cn'] . ': ' .($key+1). '; '),
            //         'children' => $children,
            //     ];
            // }
            // $product['skuTree'] = $skuTree;
            // foreach($product['skus'] as $val) {
            //     $skuList[] = $val['sku'];
            // }

        } else {
            $product['total_stock']=0;
            $product['skus'] = [];
        }

        foreach ($product['images'] as $key => $item) {
            $product['images'][$key] = env('IMAGE_URL') . $item;
        }
        // 判断是否赠送
        if ($product['give_points'] > 0) {
            $product['lable_tag'][] = '赠送' . $product['give_points'] . '积分';
        }
        if ($product['rebate'] > 0) {
            $product['lable_tag'][] = '返利' . $product['rebate'] . '%';
        }
        if ($product['share_commission'] > 0) {
            $product['lable_tag'][] = '分享佣金' . $product['share_commission'] . '%';
        }
        if ($product['price'] <= 0 && !empty($product['skus'])) {
            // skus获取skus数组里面的is_default=1的价格
            $defaultSku = array_filter($product['skus'], function ($item) {
                if ($item['is_default'] == 1){
                    return $item;
                }
            });
            $product['price'] = end($defaultSku)['price'] ?? 0;
        }
        $product['original_price'] = $product['price'];
        $product['mini_qr_img'] = empty($product['mini_qr_img'])?'': env('APP_URL') . $product['mini_qr_img'];
        $product['show_shop'] = true;

        $userId = UserService::getCurrentUserId();
        if ($userId) {
            $product['is_like'] = ProductLike::where('user_id', $userId)->where('product_id', $goodsId)->find()?1:0;
        } else {
            $product['is_like'] = 0;
        }
        unset($product['variables'], $product['skus']);
        return $product;
    }

    /**
     * 构建 skuTree 和 skuList
     *
     * @param array $variables 变量数组
     * @param array $skus      sku数组
     * @return array           包含 skuTree 和 skuList 的数组
     */
    function buildSkuTreeAndList($variables, $skus)
    {
        // 1. 构建 skuTree
        $skuTree = [];
        foreach ($variables as $varIndex => $variable) {
            $children = [];
            foreach ($variable['values'] as $valIndex => $val) {
                $children[] = [
                    "id"   => $valIndex+1,//. "_" . $valIndex,
                    "name" => $val['name']['zh_cn']
                ];
            }

            $skuTree[] = [
                "label"    => $variable['name']['zh_cn'],
                "name"     =>md5($variable['name']['zh_cn'].": "), //. ,
                "children" => $children
            ];
        }

        // 2. 构建 skuList
        $skuList = [];
        foreach ($skus as $kk=> $sku) {
            $specObj = [
                "id"=>$kk+1,//. "_" . $kk,
                "sku_id"    => $sku['id'],
                "price" => (float)$sku['price'],
                "stock" => (int)$sku['quantity'],
                "sku"   => $sku['sku'],
                "model" => $sku['model'],
                "images" => is_array($sku['images'])?env('IMAGE').$sku['images'][0]:$sku['images'],
                'origin_price'=>(float)$sku['origin_price'],
                'cost_price'=>(float)$sku['cost_price'],
                'weight'=>$sku['weight'],
                'is_default'=>$sku['is_default'],
            ];

            $sku['variants'] = empty($sku['variants'])?[]:$sku['variants'];
            foreach ($sku['variants'] as $varIndex => $variantIndex) {
                $variable = $variables[$varIndex];
                $value = $variable['values'][$variantIndex];
                $specObj[md5($variable['name']['zh_cn'] . ": ")] = (int)$variantIndex+1;//$value['name']['zh_cn'];
            }

            $skuList[] = $specObj;
        }

        return [
            "skuTree" => $skuTree,
            "skuList" => $skuList
        ];
    }


    public function getMiniQrcode($goodsId)
    {
        $uid = UserService::getCurrentUserId();
        $path= 'sub_goods/detail/goods_detail'.($uid?'?uid='.$uid:'');
        $miniQrcode = (new MiniProgramService())->getMiniQrcode([
            'scene' => 'id=' . $goodsId,
            'page' =>$path,
            'width' => 150,
            'check_path' => false,
        ]);
        if ($miniQrcode) {
            $this->productModel->where('id', $goodsId)->update(['mini_qr_img' => $miniQrcode]);
        }
        $miniQrcode = env('APP_URL') . $miniQrcode;
  
        return $miniQrcode;
    }
}
